/**
 * [调用环信api]用util
 */
var CONFIG = require('../../../common/config');
var superagent = require('superagent');

var cacheManager = require('cache-manager');
var redisStore = require('cache-manager-redis');
var redisCache = cacheManager.caching({
    store: redisStore,
    host: CONFIG.REDIS_SERVER_DOMAIN, // default value
    port: CONFIG.REDIS_SERVER_PORT, // default value
    auth_pass: CONFIG.REDIS_SERVER_PASSWORD, //
    db: CONFIG.REDIS_SERVER_DB_NAME,
    ttl: CONFIG.REDIS_SERVER_TTL
});

//------------------------------------------------------------------
// 设定参数
var HX_CONFIG = {
    // 环信
    PATH: 'https://a1.easemob.com',
    ORG_NAME: '1138170321178469',
    APP_NAME: 'onetouch',
    CLIENT_ID: 'YXA60CUK8BnQEeeLoNXY3tMRAg',
    CLIENT_SECRET: 'YXA6YlnUtTCRLhyTE9_Ng4KuGL8JiT4',
};
// redis缓存用key
var RDS_KEY_ACCESS_TOKEN_INFO = 'ITB_HX_API_ACCESS_TOKEN_INFO';

//------------------------------------------------------------------
var hxUtil = (function(){
    function hxUtil(){
        // 文档: http://docs.easemob.com/im/100serverintegration/20users
    }

    // 根据userId生成环信用户名/密码
    hxUtil.genHxUserInfo=function(userId, role){
        var uid = Number(userId||'0')||0;

        var uidFlg = 'a';
        var pwdFlg = 'b';
        if((role&128)==128) {
            // 客服
            uidFlg = 'c';
            pwdFlg = 'd';
        }

        var hxUid = parseInt(uid+172080).toString(20);
        var hxPwd = parseInt(uid+246503).toString(18);
        return {
            uid: hxUid.substring(0,2)+uidFlg+hxUid.substring(2),
            pwd: hxPwd.substring(0,2)+pwdFlg+hxPwd.substring(2)
        };
    };

    // 获取APP管理员Token
    hxUtil.getHxToken=function(callback) {
        redisCache.get(RDS_KEY_ACCESS_TOKEN_INFO, function(getErr, result){
            // 从缓存获取
            if (getErr==null && result){
                var tokenInfo = result;
                // 是否过期
                if(tokenInfo && !!tokenInfo.access_token &&
                    (new Date().getTime()) < (Number(tokenInfo.create_at||'0') + Number(tokenInfo.expires_in||'0')*1000)
                ){
                    console.log('===> [GetHxToken] from Cache');
                    return callback(null, tokenInfo.access_token);
                }
            }

            // 重新获取
            var url = HX_CONFIG.PATH+ '/'+ HX_CONFIG.ORG_NAME + '/' + HX_CONFIG.APP_NAME + '/token';
            var param = {
                grant_type: 'client_credentials',
                client_id: HX_CONFIG.CLIENT_ID,
                client_secret: HX_CONFIG.CLIENT_SECRET,
            };
            superagent.post(url)
                .set('Content-Type', 'application/json')
                .send(param)
                .end(function(err, res){
                    if(err) {
                        return callback(err, null);
                    }

                    if(res && res.text) {
                        console.log('GetHxToken ret: '+res);
                        var retJson = JSON.parse(res.text);
                        //{
                        //    "access_token": "YWMtWY779DgJEeS2h9OR7fw4QgAAAUmO4Qukwd9cfJSpkWHiOa7MCSk0MrkVIco",
                        //    "expires_in": 5184000,// token 有效时间，以秒为单位
                        //    "application": "c03b3e30-046a-11e4-8ed1-5701cdaaa0e4"
                        //}

                        var tokenInfo = {
                            access_token: retJson.access_token || '',
                            expires_in: retJson.expires_in || 0,
                            create_at: new Date().getTime(),// TODO
                        };

                        redisCache.set(RDS_KEY_ACCESS_TOKEN_INFO, tokenInfo, {ttl:tokenInfo.expires_in}, function(setErr){
                            console.log("===> [GetHxToken] set NewToken to Redis!");
                            return callback(null, tokenInfo.access_token);
                        });

                    } else {
                        return callback('GetHxToken Err!', null);
                    }
                }
            );
        });
    };

    // 获取IM用户[单个]
    hxUtil.getHxUser = function(userName, callback) {
        if(!userName || userName.length==0) {
            return callback('Invalid HX UserName!', null);
        }

        hxUtil.getHxToken(function(getErr, hxToken){
            if(!hxToken || hxToken.length==0) {
                return callback('Get HX Token Err!', null);
            }

            var url = HX_CONFIG.PATH+ '/'+ HX_CONFIG.ORG_NAME + '/' + HX_CONFIG.APP_NAME + '/users/' + userName;
            superagent.get(url)
                .set('Authorization', 'Bearer '+hxToken)
                .end(function(err, res){
                    if(err) {
                        return callback(err, null);
                    }

                    if(res && res.text) {
                        var retJson = JSON.parse(res.text);
                        return callback(null, retJson);

                    } else {
                        return callback('GetHxUser Err!', null);
                    }
                }
            );
        });
    };

    // 注册IM用户[单个]
    hxUtil.regHxUser = function(userName, password, callback) {
        if(!userName || userName.length==0) {
            return callback('Invalid HX UserName!', null);
        }

        hxUtil.getHxToken(function(getErr, hxToken) {
            if (!hxToken || hxToken.length == 0) {
                return callback('Get HX Token Err!', null);
            }

            var url = HX_CONFIG.PATH+ '/'+ HX_CONFIG.ORG_NAME + '/' + HX_CONFIG.APP_NAME + '/users';
            var param = {
                username: userName||'',
                password: password||'',
            };
            superagent.post(url)
                .set({'Content-Type':'application/json', 'Authorization':'Bearer '+hxToken})
                .send(param)
                .end(function(err, res){
                    if(err) {
                        return callback(err, null);
                    }

                    if(res && res.text) {
                        var retJson = JSON.parse(res.text);
                        return callback(null, retJson);

                    } else {
                        return callback('RegHxUser Err!', null);
                    }
                }
            );
        });
    };

    // 给IM用户添加好友
    hxUtil.addHxFriend = function(ownerNm, friendNm, callback) {
        if(!ownerNm || ownerNm.length==0 || !friendNm || friendNm.length==0) {
            return callback('Invalid HX UserName!', null);
        }

        hxUtil.getHxToken(function(getErr, hxToken) {
            if (!hxToken || hxToken.length == 0) {
                return callback('Get HX Token Err!', null);
            }

            var url = HX_CONFIG.PATH+ '/'+ HX_CONFIG.ORG_NAME + '/' + HX_CONFIG.APP_NAME + '/users/'
                    + ownerNm + '/contacts/users/' + friendNm;
            superagent.post(url)
                .set('Authorization','Bearer '+hxToken)
                .send({})
                .end(function(err, res){
                    if(err) {
                        return callback(err, null);
                    }

                    if(res && res.text) {
                        var retJson = JSON.parse(res.text);
                        return callback(null, retJson);

                    } else {
                        return callback('AddHxFriend Err!', null);
                    }
                }
            );
        });
    };

    // 解除IM用户的好友关系
    hxUtil.delHxFriend = function(ownerNm, friendNm, callback) {
        if(!ownerNm || ownerNm.length==0 || !friendNm || friendNm.length==0) {
            return callback('Invalid HX UserName!', null);
        }

        hxUtil.getHxToken(function(getErr, hxToken) {
            if (!hxToken || hxToken.length == 0) {
                return callback('Get HX Token Err!', null);
            }

            var url = HX_CONFIG.PATH+ '/'+ HX_CONFIG.ORG_NAME + '/' + HX_CONFIG.APP_NAME + '/users/'
                + ownerNm + '/contacts/users/' + friendNm;
            superagent.del(url)
                .set('Authorization','Bearer '+hxToken)
                .end(function(err, res){
                    if(err) {
                        return callback(err, null);
                    }

                    if(res && res.text) {
                        var retJson = JSON.parse(res.text);
                        return callback(null, retJson);

                    } else {
                        return callback('DelHxFriend Err!', null);
                    }
                }
            );
        });
    };

    // return
    return hxUtil;
})();


//------------------------------------------------------------------
module.exports = hxUtil;



